package com.achobeta.recruitment.utils;

import com.achobeta.recruitment.config.QRCodeConstant;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.UUID;

public class QRCodeGenerator {

    public static String loadQRCode(String url) {
        int width = 300; // 二维码图片宽度
        int height = 300; // 二维码图片高度
        String format = "jpeg"; // 二维码图片格式
        String path = null;
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width, height);
            BufferedImage qrCodeImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            qrCodeImage.createGraphics();

            Graphics2D graphics = (Graphics2D) qrCodeImage.getGraphics();
            graphics.setColor(Color.WHITE);
            graphics.fillRect(0, 0, width, height);
            graphics.setColor(Color.BLACK);

            for (int i = 0; i < width; i++) {
                for (int j = 0; j < height; j++) {
                    if (bitMatrix.get(i, j)) {
                        graphics.fillRect(i, j, 1, 1);
                    }
                }
            }
            path = QRCodeConstant.DOWNLOAD_PATH_PREFIX + UUID.randomUUID().toString().replaceAll("-", "") + "." + format;
            ImageIO.write(qrCodeImage, format, new File(path));
            System.out.println("二维码已成功生成并保存到本地！");
        } catch (Exception e) {
            System.err.println("生成二维码时出现错误：" + e.getMessage());
        }
        return path;
    }
}